var needle = require('needle');
var mongoose = require('mongoose');
var imageHandler = require('../service/imageHandler');
var redisManager = require('../proxy').RedisManager;
var User = require('../proxy').User;
var logger = require('../service/Logger');
var DB = require('../entity').DB;
var grid = mongoose.mongo.Grid(DB);


exports.getImg = function(req, res, next){
    var userId = req.params.userId;
    DB.collection('fs.files').find({filename: userId+'.jpg'}).toArray(function(err, items){
        if(items.length > 0){
            grid.get(items[0]._id, function(err, data){
                if(err) return res.send(false)
                res.setHeader("Content-Type", 'image/jpeg');
                res.setHeader('Cache-Control', 'public, max-age= 0');//2880000000
                return res.send(data);
            })
        }else{
            return res.send(false)
        }
    })
}

exports.refreshHeadimg = function(req, res, next){
    var me = req.params.currentUser;
    User.getUserById(me.id, function(err, user){
        if(err){
            logger.error(err.stack);
        }
        if(user.headimg){
            imageHandler.handleAndSave(user.headimg, {
                size: 64,
                quality: 80,
                name: me.id+'.jpg'
            }, function(err, data){
                if(err) return res.send({error: err.message});
                res.send({data: data})
            });
        }else{
            res.send(null)
        }
    })
    /*redisManager.getAccesstoken(function(err, token){
        var url = 'https://api.weixin.qq.com/cgi-bin/user/info?' +
            'access_token='+token+'&openid='+me.openid+'&lang=zh_CN';
        var option = {headers: {'Content-Type': 'application/json'}}
        needle.get(url, option, function(err, resp, body){
            if(err) return res.send({error: err.message});
            var userInfo = body//JSON.parse(body);
            // 删除原头像
            DB.collection('fs.files').remove({filename: me.id+'.jpg'}, function(err, result){
                if(err) return res.send({error: err.message});
                //保存新头像
                imageHandler.handleAndSave(userInfo.headimgurl, {
                    size: 64,
                    quality: 80,
                    name: me.id+'.jpg'
                }, function(err, data){
                    if(err) return res.send({error: err.message});
                    res.send({data: data})
                });
            })
        })
    })*/
}
